//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package ciicos.views.service.impl;

import ciicos.base.model.filter.RuleInfo;
import ciicos.model.visiual.superQuery.ConditionJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryConditionModel;
import ciicos.model.visiual.superQuery.SuperQueryJsonModel;
import ciicos.permission.model.authorize.AuthorizeConditionModel;
import ciicos.permission.service.AuthorizeService;
import ciicos.permission.util.GenUtil;
import ciicos.util.GeneraterSwapUtil;
import ciicos.util.JsonUtil;
import ciicos.util.ServletUtil;
import ciicos.util.StringUtil;
import ciicos.util.UserProvider;
import ciicos.views.entity.ViewsScriptEntity;
import ciicos.views.mapper.ViewsScriptMapper;
import ciicos.views.model.viewsscript.ViewsScriptForm;
import ciicos.views.model.viewsscript.ViewsScriptPagination;
import ciicos.views.service.ViewsScriptService;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ViewsScriptServiceImpl extends ServiceImpl<ViewsScriptMapper, ViewsScriptEntity> implements ViewsScriptService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private AuthorizeService authorizeService;

    public List<ViewsScriptEntity> getList(ViewsScriptPagination viewsScriptPagination) {
        return this.getTypeList(viewsScriptPagination, viewsScriptPagination.getDataType());
    }

    public List<ViewsScriptEntity> getTypeList(ViewsScriptPagination viewsScriptPagination, String dataType) {
        String userId = this.userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList();
        int total = 0;
        int viewsScriptNum = 0;
        QueryWrapper<ViewsScriptEntity> viewsScriptQueryWrapper = new QueryWrapper();
        List<String> allSuperIDlist = new ArrayList();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(viewsScriptPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = (SuperQueryJsonModel)JsonUtil.getJsonToBean(viewsScriptPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);

            for(ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null && Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                    conditionjson.setFieldValue("[]");
                }

                conditionjson.setTableName(tableName);
            }

            List<String> allSuperList = new ArrayList();
            List<List<String>> intersectionSuperList = new ArrayList();
            int viewsScriptNum1 = 0;
            QueryWrapper<ViewsScriptEntity> viewsScriptSuperWrapper = new QueryWrapper();
            viewsScriptNum1 = this.generaterSwapUtil.getCondition(new SuperQueryConditionModel(viewsScriptSuperWrapper, superQueryList, matchLogic, "views_script"), new ViewsScriptEntity(), viewsScriptNum1);
            if (viewsScriptNum1 > 0) {
                List<String> viewsScriptList = (List)this.list(viewsScriptSuperWrapper).stream().map(ViewsScriptEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(viewsScriptList);
                intersectionSuperList.add(viewsScriptList);
            }

            superOp = matchLogic;
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = this.generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }

        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");
        if (isPc && pcPermission && !this.userProvider.get().getIsAdministrator()) {
            Object viewsScriptObj = this.authorizeService.getCondition(new AuthorizeConditionModel(viewsScriptQueryWrapper, viewsScriptPagination.getMenuId(), "views_script"));
            if (ObjectUtil.isEmpty(viewsScriptObj)) {
                return new ArrayList();
            }

            viewsScriptQueryWrapper = (QueryWrapper)viewsScriptObj;
            if (viewsScriptQueryWrapper.getExpression().getNormal().size() > 0) {
                ++viewsScriptNum;
            }
        }

        if (!isPc && appPermission && !this.userProvider.get().getIsAdministrator()) {
            Object viewsScriptObj = this.authorizeService.getCondition(new AuthorizeConditionModel(viewsScriptQueryWrapper, viewsScriptPagination.getMenuId(), "views_script"));
            if (ObjectUtil.isEmpty(viewsScriptObj)) {
                return new ArrayList();
            }

            viewsScriptQueryWrapper = (QueryWrapper)viewsScriptObj;
            if (viewsScriptQueryWrapper.getExpression().getNormal().size() > 0) {
                ++viewsScriptNum;
            }
        }

        if (isPc && ObjectUtil.isNotEmpty(viewsScriptPagination.getName())) {
            ++viewsScriptNum;
            viewsScriptQueryWrapper.lambda().like(ViewsScriptEntity::getName, viewsScriptPagination.getName());
        }

        List<String> intersection = this.generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }

            viewsScriptQueryWrapper.lambda().in(ViewsScriptEntity::getId, intersection);
        }

        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            viewsScriptQueryWrapper.lambda().and(t->t.in(ViewsScriptEntity::getId, finalAllSuperIDlist));
        }

        if (StringUtil.isEmpty(viewsScriptPagination.getSidx())) {
            viewsScriptQueryWrapper.lambda().orderByDesc(ViewsScriptEntity::getCreatortime);
        } else {
            try {
                String sidx = viewsScriptPagination.getSidx();
                ViewsScriptEntity viewsScriptEntity = new ViewsScriptEntity();
                Field declaredField = viewsScriptEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                viewsScriptQueryWrapper = "asc".equals(viewsScriptPagination.getSort().toLowerCase()) ? viewsScriptQueryWrapper.orderByAsc(value) : viewsScriptQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if (!"0".equals(dataType)) {
            return this.list(viewsScriptQueryWrapper);
        } else if ((total <= 0 || AllIdList.size() <= 0) && total != 0) {
            List<ViewsScriptEntity> list = new ArrayList();
            return viewsScriptPagination.setData(list, (long)list.size());
        } else {
            Page<ViewsScriptEntity> page = new Page(viewsScriptPagination.getCurrentPage(), viewsScriptPagination.getPageSize());
            IPage<ViewsScriptEntity> userIPage = this.page(page, viewsScriptQueryWrapper);
            return viewsScriptPagination.setData(userIPage.getRecords(), userIPage.getTotal());
        }
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String tableName) {
        try {
            wrapper.apply(" 1=1 ", new Object[0]);

            for(RuleInfo info : this.generaterSwapUtil.getFilterCondition(id)) {
                String field = info.getField();
                if ((!"main".equals(type) || !field.contains("-")) && (!"main".equals(type) || !field.contains("_jnpf_")) && (!"sub".equals(type) || field.contains("-")) && (!"sub-jnpf".equals(type) || field.contains("_jnpf_"))) {
                    String fieldName = field;
                    String table = "";
                    if (field.contains("-")) {
                        fieldName = field.split("-")[1];
                    }

                    if (field.contains("_jnpf_")) {
                        fieldName = field.split("_jnpf_")[1];
                        table = field.split("_jnpf_")[0];
                        table = table.replace("jnpf_", "");
                    }

                    if (!"sub-jnpf".equals(type) || tableName.equals(table)) {
                        Field declaredField = aClass.getDeclaredField(fieldName);
                        declaredField.setAccessible(true);
                        String fieldDb = ((TableField)declaredField.getAnnotation(TableField.class)).value();
                        GenUtil genUtil = (GenUtil)JsonUtil.getJsonToBean(info, GenUtil.class);
                        genUtil.solveValue(wrapper, fieldDb);
                    }
                }
            }

            return wrapper;
        } catch (Exception var15) {
            return wrapper;
        }
    }

    public ViewsScriptEntity getInfo(String id) {
        QueryWrapper<ViewsScriptEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(ViewsScriptEntity::getId, id);
        return (ViewsScriptEntity)this.getOne(queryWrapper);
    }

    public void create(ViewsScriptEntity entity) {
        this.save(entity);
    }

    public boolean update(String id, ViewsScriptEntity entity) {
        return this.updateById(entity);
    }

    public void delete(ViewsScriptEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }

    }

    public String checkForm(ViewsScriptForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }

        if (ObjectUtil.isNotEmpty(form.getName())) {
            QueryWrapper<ViewsScriptEntity> nameWrapper = new QueryWrapper();
            nameWrapper.lambda().eq(ViewsScriptEntity::getName, form.getName());
            if (isUp) {
                nameWrapper.lambda().ne(ViewsScriptEntity::getId, id);
            }

            if ((int)this.count(nameWrapper) > 0) {
                ++total;
                countRecover = "名称";
            }
        }

        return countRecover;
    }
}
